package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rs.mbs2.epics.server.entity.Album;
import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.session.dao.localinterface.AlbumDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@SuppressWarnings("serial")
public class ViewUserController extends HttpServlet {

	@EJB
	private UserDaoLocal userDao;

	@EJB
	private AlbumDaoLocal albumDao;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("ViewUserController.doGet()");

		String idString = request.getParameter("id");
		Integer id = Integer.parseInt(idString);

		User viewedUser = userDao.findById(id);
		request.setAttribute("viewedUser", viewedUser);

		List<Album> albums = albumDao.findAllAlbumsFromUser(viewedUser.getId());
		request.setAttribute("userAlbums", albums);

		User loggedUser = (User) request.getSession().getAttribute("user");

		if(loggedUser != null) {
			User user = userDao.findById(loggedUser.getId());
			if(user.getFollowedUsers().contains(viewedUser))
				request.setAttribute("followed", true);
			else
				request.setAttribute("followed", false);
		}


		getServletContext().getRequestDispatcher("/viewUser.jsp").forward(request, response);
		return;
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
